'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { notesApi, knowledgeBasesApi } from '@/lib/api';
import { 
  BookOpen, 
  Plus, 
  Search, 
  Edit, 
  Trash2, 
  Database,
  FileText,
  Calendar,
  Eye,
  Zap
} from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import toast from 'react-hot-toast';

interface Note {
  id: string;
  title: string;
  content_preview: string;
  owner_name: string;
  knowledge_base_id?: string;
  is_vectorized: boolean;
  is_public: boolean;
  word_count: number;
  document_count: number;
  created_at: string;
  updated_at?: string;
}

interface KnowledgeBase {
  id: string;
  name: string;
}

export default function NotesPage() {
  const router = useRouter();
  const { user } = useAuthStore();
  
  const [notes, setNotes] = useState<Note[]>([]);
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedKB, setSelectedKB] = useState<string>('all');
  const [deleteConfirm, setDeleteConfirm] = useState<{isOpen: boolean, noteId: string, noteTitle: string}>({
    isOpen: false,
    noteId: '',
    noteTitle: ''
  });

  useEffect(() => {
    loadNotes();
    loadKnowledgeBases();
  }, [searchQuery, selectedKB]);

  const loadNotes = async () => {
    try {
      setLoading(true);
      const params: any = {};
      if (searchQuery) params.search = searchQuery;
      if (selectedKB !== 'all') params.knowledge_base_id = selectedKB;
      
      const data = await notesApi.list(params);
      setNotes(data);
    } catch (error) {
      console.error('加载笔记失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadKnowledgeBases = async () => {
    try {
      const resp = await knowledgeBasesApi.list();
      const list = Array.isArray(resp) ? resp : (resp?.items ?? []);
      setKnowledgeBases(list);
    } catch (error) {
      console.error('加载知识库失败:', error);
    }
  };

  const handleDeleteClick = (id: string, title: string) => {
    setDeleteConfirm({ isOpen: true, noteId: id, noteTitle: title });
  };

  const handleDeleteConfirm = async () => {
    const { noteId } = deleteConfirm;
    try {
      await notesApi.delete(noteId);
      toast.success('删除成功');
      loadNotes();
    } catch (error: any) {
      toast.error('删除失败: ' + error.message);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            📝 笔记中心
          </h1>
          <p className="mt-2 text-gray-600 dark:text-white/60">
            管理你的知识笔记，支持 Markdown 格式
          </p>
        </div>
        <GlassButton
          variant="primary"
          onClick={() => router.push('/dashboard/notes/editor')}
        >
          <Plus className="mr-2 h-5 w-5" />
          新建笔记
        </GlassButton>
      </div>

      {/* 搜索和筛选 */}
      <GlassCard className="p-6">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400 dark:text-white/40" />
              <input
                type="text"
                placeholder="搜索笔记标题或内容..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2 bg-white/60 dark:bg-gray-800 border border-gray-300/40 dark:border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/50 text-gray-900 dark:text-white"
              />
            </div>
          </div>
          <div className="w-64">
            <select
              value={selectedKB}
              onChange={(e) => setSelectedKB(e.target.value)}
              className="w-full px-4 py-2 bg-white/60 dark:bg-gray-800 border border-gray-300/40 dark:border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/50 text-gray-900 dark:text-white"
            >
              <option value="all">全部笔记</option>
              <option value="private">私有笔记</option>
              {knowledgeBases.map((kb) => (
                <option key={kb.id} value={kb.id}>
                  {kb.name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </GlassCard>

      {/* 笔记列表 */}
      {loading ? (
        <div className="flex justify-center items-center h-64">
          <div className="text-gray-500 dark:text-white/60">加载中...</div>
        </div>
      ) : notes.length === 0 ? (
        <GlassCard className="p-12 text-center">
          <BookOpen className="mx-auto h-16 w-16 text-gray-400 dark:text-white/40 mb-4" />
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            还没有笔记
          </h3>
          <p className="text-gray-600 dark:text-white/60 mb-6">
            创建第一个笔记，开始记录你的知识
          </p>
          <GlassButton
            variant="primary"
            onClick={() => router.push('/dashboard/notes/editor')}
          >
            <Plus className="mr-2 h-5 w-5" />
            创建笔记
          </GlassButton>
        </GlassCard>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {notes.map((note) => (
            <GlassCard
              key={note.id}
              className="p-6 hover:shadow-xl transition-shadow cursor-pointer group"
              onClick={() => router.push(`/dashboard/notes/editor?id=${note.id}`)}
            >
              <div className="flex items-start justify-between mb-3">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white line-clamp-2 flex-1">
                  {note.title}
                </h3>
                <div className="flex gap-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      router.push(`/dashboard/notes/editor?id=${note.id}`);
                    }}
                    className="p-1.5 rounded-lg hover:bg-blue-100 dark:hover:bg-blue-500/20 text-blue-500"
                    title="编辑"
                  >
                    <Edit className="h-4 w-4" />
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteClick(note.id, note.title);
                    }}
                    className="p-1.5 rounded-lg hover:bg-red-100 dark:hover:bg-red-500/20 text-red-500"
                    title="删除"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>

              <p className="text-sm text-gray-600 dark:text-white/60 mb-4 line-clamp-3">
                {note.content_preview}
              </p>

              <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-white/50 mb-3">
                <span className="flex items-center gap-1">
                  <FileText className="h-3.5 w-3.5" />
                  {note.word_count} 字
                </span>
                {note.document_count > 0 && (
                  <span className="flex items-center gap-1">
                    <Database className="h-3.5 w-3.5" />
                    {note.document_count} 个文档
                  </span>
                )}
                <span className="flex items-center gap-1">
                  <Calendar className="h-3.5 w-3.5" />
                  {formatDate(note.updated_at || note.created_at)}
                </span>
              </div>

              <div className="flex items-center gap-2 flex-wrap">
                {note.is_public && (
                  <span className="inline-flex items-center gap-1 px-2 py-1 text-xs bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400 rounded-full">
                    <Eye className="h-3 w-3" />
                    公开
                  </span>
                )}
                {note.is_vectorized && (
                  <span className="inline-flex items-center gap-1 px-2 py-1 text-xs bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400 rounded-full">
                    <Zap className="h-3 w-3" />
                    已向量化
                  </span>
                )}
                {!note.is_public && (
                  <span className="inline-flex items-center gap-1 px-2 py-1 text-xs bg-gray-100 dark:bg-gray-500/20 text-gray-700 dark:text-gray-400 rounded-full">
                    私有
                  </span>
                )}
              </div>
            </GlassCard>
          ))}
        </div>
      )}

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, noteId: '', noteTitle: '' })}
        onConfirm={handleDeleteConfirm}
        title="删除笔记"
        message={`确定要删除笔记"${deleteConfirm.noteTitle}"吗？此操作不可恢复。`}
        confirmText="删除"
        cancelText="取消"
        variant="danger"
      />
    </div>
  );
}

